﻿using OperationPlugins.Mvc.Filters;
using System;
using System.Web.Mvc;
using TimeProject.Engine;
using TimeProject.Engine.DbContent;
using TimeProject.Engine.DbModels;
using TimeProject.WebSite.ViewModels;
using WebMatrix.WebData;

namespace TimeProject.WebSite.Controllers
{
    public partial class TimeProjectController
    {
        [HttpGet]
        [CurrentOperation(TimeProjectOperations.ChangePassword)]
        public ActionResult ChangePassword()
        {
            ChangePasswordViewModel vm = new ChangePasswordViewModel();
            return View(vm);
        }

        [HttpPost]
        [CurrentOperation(TimeProjectOperations.ChangePassword)]
        public ActionResult ChangePassword(ChangePasswordViewModel vm)
        {
            return Json(vm, () =>
            {
                User user = Db.GetUser(UserId);

                bool succeed;
                try
                {
                    succeed = WebSecurity.ChangePassword(RequestContext.Current.CurrentUser.Username, vm.OldPassword, vm.NewPassword);
                }
                catch (Exception)
                {
                    succeed = false;
                }

                if (succeed)
                {
                    Db.UserActivities.Add(new UserActivity
                    {
                        UserId = user.Id,
                        Type = UserActivityType.ChangePassword,
                        Created = RequestContext.Current.RequestTimestamp,
                        Creator = RequestContext.Current.RequestUsername
                    });

                    if (SaveDbContext(vm))
                    {
                        WebSecurity.Logout();
                        vm.Messages.AddNofificationMessage("Your password has been changed!");
                        vm.RedirectTo("Login");
                    }
                }
                else
                {
                    vm.Messages.AddErrorMessage("The current password is incorrect or the new password is invalid.");
                }
            });
        }

    }
}